//---------------------------------------------------------------------
// Author: jachymko
//
// Description: Base class for all tab expansion caches. Initializes the
//              implementations on a background thread.
//
// Creation Date: Jan 8, 2007
//---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Threading;

using Pscx.Commands.TabExpansion.Caches;

namespace Pscx.Commands.TabExpansion
{
    abstract class TabExpansionCache
    {
        internal abstract void OnInitialize();

        private readonly object _syncRoot = new object();
        private readonly Thread _thread;

        public TabExpansionCache()
        {
            _thread = new Thread(OnInitialize);
        }

        public void EnsureInitializedAsync()
        {
            Initialize(false);
        }

        public void EnsureInitialized()
        {
            Initialize(true);
        }

        private void Initialize(bool wait)
        {
            lock (_syncRoot)
            {
                if (_thread.ThreadState == ThreadState.Unstarted)
                {
                    _thread.IsBackground = true;
                    _thread.Priority = ThreadPriority.Lowest;
                    _thread.Name = GetType().Name + ".Initialize";
                    _thread.Start();
                }
            }

            if (wait)
            {
                _thread.Join();
            }
        }
    }
}
